<template>
  <div class="wtable">
    <el-table
      ref="tableRef"
      v-bind="$attrs"
      :max-height="maxHeightVal"
      :data="getData()"
      :row-style="rowStyle"
      :cell-style="handCellStyle"
      :span-method="arraySpanMethod"
      :stripe="stripe"
      :tooltip-effect="tooltipEffect"
      highlight-current-row
      @selection-change="handleSelectionChange"
      @expand-change="expandChange"
      @sort-change="sortChange"
      @select="select"
      @select-all="selectall"
      @row-click="rowClick"
      @cell-dblclick="clickCopy"
    >
      <el-table-column
        v-if="selection"
        type="selection"
        :fixed="selectFixed"
        width="45"
      />
      <el-table-column
        v-if="order"
        label="排序"
        :index="indexMethod"
        :fixed="orderFixed"
        type="index"
        width="75"
      />
      <slot></slot>
    </el-table>

    <div v-if="pagination" class="edu-pagination">
      <div class="refresh">
        <el-button
          v-if="paginationShowRefresh"
          icon="Refresh"
          :text="true"
          @click="refreshBtnClick"
        />
      </div>
      <el-pagination
        v-model="pageNum"
        :page-sizes="pageSizes ? pageSizes : [20, 50, 100, 500, 1000]"
        :page-size="pageSize"
        :total="getTotal()"
        :layout="paginationLayout"
        :small="paginationSmall"
        @size-change="onPageSizeChange"
        @current-change="pageChange"
      />
    </div>
  </div>
</template>
<script>
import fetch from "@/utils/fetch";
import { ElTableColumn } from "element-plus";

export default {
  name: "edu-table",
  props: {
    maxHeight: {
      type: Number,
      // default: 450
    },
    orderFixed: {
      // 序号是否固定
      type: Boolean,
      default: false,
    },
    selectFixed: {
      // 复选框是否固定
      type: Boolean,
      default: false,
    },
    selection: {
      // 是否多选
      type: Boolean,
      default: true,
    },
    order: {
      // 是否加上序号
      type: Boolean,
      default: true,
    },
    pagination: {
      // 是否使用分页
      type: Boolean,
      default: true,
    },
    data: {
      type: Array,
      default: () => [],
    },
    rowStyle: {
      default: () => {
        20;
      },
    },
    total: {
      // 总数
      type: Number,
      default: 0,
    },
    pageNum: {
      // 当前页码
      type: Number,
      default: 1,
    },
    pageSize: {
      // 每页显示数
      type: Number,
      default: 20,
    },
    url: {
      type: String,
      default: null,
    },
    merge: {
      type: Boolean,
      default: false,
    },
    defaultIndex: {
      type: Boolean,
      default: false,
    },
    cellSpan: {
      type: Object,
      default: null,
    },
    paginationLayout: {
      default: "->, total, prev, pager, next, jumper",
    },
    paginationSmall: {
      default: false,
    },
    paginationShowRefresh: {
      default: false,
    },
    cellBackgroundColor: {
      type: String,
      default: null,
    },
    pageSizes: {
      type: Array,
      default: null,
    },
    tooltipEffect: {
      type: String,
      default: "light",
    },
    stripe: {
      type: Boolean,
      default: true,
    },
    isRowClickChangeRowSelection: {
      // 点击行是否出发复选框选中事件
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      dataList: [],
      total_: 0,
      condition: null,
      selectionDatas: null,
      maxHeightVal: null,
    };
  },
  beforeCreate() {
    // console.log(ElTableColumn.props);
    // 全局字段支持排序 但无法过滤操作 和 选择框
    ElTableColumn.props.sortable = { default: true, type: Boolean };
    ElTableColumn.props.formatter = {
      type: Function,
      default: function (row, column, cellValue, index) {
        // console.log(cellValue);
        // console.log(index);
        if (cellValue === null || cellValue === "" || cellValue === undefined) {
          return "--";
        } else {
          return cellValue;
        }
      },
    };
  },
  mounted() {
    // 指定字段支持排序
    // this.$refs.tableRef.sort('studentId', 'descending')
    // console.log(this.$refs.tableRef.columns);
    // this.$refs.tableRef.columns.map((e) => {
    //   // console.log(e);
    //   if (e.label == "操作" || e.type == "selection") {
    //     e.sortable = false;
    //   } else {
    //     e.sortable = true;
    //   }
    // });
    // setTimeout(() => {
    //   this.setMaxHeight();
    // }, 1000);
  },
  methods: {
    // 点击复制单元格内容
    clickCopy(row, field, cell, event) {
      // console.log(row);
      // console.log(field);
      // console.log(cell);
      // console.log(event);
      // console.log(event.target);

      let target = event.target;
      let classNames = target.getAttribute("class");
      let width = target.offsetWidth - 20; //padding距离

      // 创建临时dom用来获取文字真实宽度
      let TemporaryTag = document.createElement("span");
      TemporaryTag.innerText = row[field.property];
      TemporaryTag.className = "tempTextWidth";
      document.querySelector("body").appendChild(TemporaryTag);
      let tempTextWidth = document.querySelector(".tempTextWidth").offsetWidth;
      document.querySelector(".tempTextWidth").remove();

      // console.log(width);
      // console.log(tempTextWidth);
      // console.log(tempTextWidth > width);

      if (tempTextWidth > width) {
        let val = row[field.property];

        if (val) {
          let input = document.createElement("input");
          input.setAttribute("readonly", "readonly");
          input.value = val;
          document.body.appendChild(input);
          input.select();
          document.execCommand("copy");
          document.body.removeChild(input);

          this.$notify({
            title: "成功",
            message: "内容已复制成功,ctrl+v粘贴",
            type: "success",
          });
        }
      }
    },
    setMaxHeight() {
      // 外部设置的固定值
      if (this.maxHeight) {
        this.maxHeightVal = this.maxHeight;
      }

      // 计算高度
      // 筛选条件高度
      let filterForm = document.getElementsByClassName("conditionFilter");
      let filterFormHeight =
        (filterForm.length > 0 && filterForm[0].offsetHeight) || 0;
      // el-card.desc
      let cardDesc = document.querySelectorAll(".el-card.desc");
      let cardDescFormHeight =
        (cardDesc.length > 0 && cardDesc[0].offsetHeight + 10) || 0;
      // cardMiniBar
      let cardMiniBar = document.querySelectorAll(".cardMiniBar");
      let cardMiniBarFormHeight =
        (cardMiniBar.length > 0 && cardMiniBar[0].offsetHeight + 10) || 0;
      // console.log(cardDescFormHeight);
      // console.log(cardMiniBarFormHeight);
      // 标题高度
      let conditionTitle = document.getElementsByClassName("condition-title");
      let conditionTitleHeight =
        conditionTitle.length > 0 && conditionTitle[0].offsetHeight;
      let bodyHeight =
        document.body.offsetHeight -
        35 -
        64 -
        10 * 2 -
        filterFormHeight -
        cardDescFormHeight -
        cardMiniBarFormHeight -
        15 * 2 -
        conditionTitleHeight -
        50;
      // console.log(filterForm);
      // console.log(filterFormHeight);
      // console.log(conditionTitle);
      // console.log(conditionTitleHeight);
      let height = bodyHeight < 400 ? 400 : bodyHeight;
      // console.log('height'+height);
      // console.log('bodyHeight'+bodyHeight);
      this.maxHeightVal = height;
      // this.maxHeightVal = bodyHeight
    },
    indexMethod(index) {
      if (this.defaultIndex) return index;
      else return (this.pageNum - 1) * this.pageSize + index + 1;
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      // 合并行
      if (this.cellSpan) {
        for (let key in this.cellSpan) {
          if (column.property == key) {
            const _row = this.cellSpan[key][rowIndex];
            const _col = _row > 0 ? 1 : 0;
            return {
              rowspan: _row,
              colspan: _col,
            };
          }
        }
      }
      if (!this.merge) return;
      let { columnList } = row;
      if (!columnList) return;
      let mergeData = columnList.filter((el) => {
        return el.index === columnIndex;
      });
      if (mergeData.length === 1) {
        let { index, rowspan, colspan } = mergeData[0];
        if (index === columnIndex) {
          return {
            rowspan,
            colspan,
          };
        }
      }
    },
    getData() {
      if (this.url) {
        return this.dataList;
      }
      return this.data;
    },
    getTotal() {
      if (this.url) {
        return this.total_;
      }
      return this.total;
    },
    handleSelectionChange(val) {
      this.selectionDatas = val;
      this.$emit("selection-change", val);
    },
    // 设置cell背景颜色，根据子组件传参cellBackgroundColor cell颜色，cellFillingList 在row中传递要填充的数组
    handCellStyle({ row, column, rowIndex, columnIndex }) {
      if (this.cellBackgroundColor && row.cellFillingList) {
        let tempCellFillingList = row.cellFillingList;
        if (tempCellFillingList.includes(columnIndex)) {
          return this.cellBackgroundColor;
        }
      } else {
        return null;
      }
    },
    onPageSizeChange(size) {
      this.pageSize = size;
      // 当前页展示列表数量(pageSize)发生变化时默认将请求的页数设置为1
      this.pageNum = 1;
      this.pageChange();
    },
    pageChange(currentPage) {
      if (this.url) {
        this.search(this.condition);
      }
      this.$emit("page-change", {
        pageSize: this.pageSize,
        pageNum: currentPage,
      });
    },
    getCheckData(key) {
      let result = [];
      if (!_.isEmpty(this.selectionDatas)) {
        if (key) {
          for (const data of this.selectionDatas) {
            result.push(data[key]);
          }
        } else {
          result = this.selectionDatas;
        }
      }
      return result;
    },
    clearSelection() {
      this.$refs.tableRef && this.$refs.tableRef.clearSelection();
    },
    clearTable() {
      this.clearSelection();
      this.dataList = [];
      this.total_ = 0;
    },
    search(data) {
      this.condition = data;
      let param = {
        pageNum_: this.pageNum,
        pageSize_: this.pageSize,
        condition: data,
      };
      if (!this.pagination) {
        param = data;
      }
      return fetch({
        url: this.url,
        method: "post",
        data: param,
      })
        .then((res) => {
          if (!_.isNil(res.data)) {
            this.dataList = res.data.list;
            this.total_ =
              res.data.total_ == null ? res.data.total : res.data.total_;
            this.$emit("load-done", this.dataList);
          } else {
            this.dataList = [];
            this.total_ = 0;
          }
          return res;
        })
        .catch((error) => {
          this.dataList = [];
          this.total_ = 0;
        });
    },
    sortChange(column, prop, order) {
      this.$emit("sort-change", column, prop, order, this.dataList);
    },
    refreshDirectNameData(dataList) {
      this.dataList = dataList;
    },
    expandChange(row, expandedRows) {
      this.$emit("expandChange", row, expandedRows);
    },
    select(selection, row) {
      this.$emit("select", selection, row);
    },
    selectall(selection) {
      this.$emit("select-all", selection);
    },
    refreshBtnClick() {
      if (this.url) {
        this.search(this.condition);
      }
      this.$emit("refresh-click");
    },
    rowClick(row, column, event) {
      this.toggleRowSelection(row);
    },
    toggleRowSelection(row, flag) {
      this.isRowClickChangeRowSelection &&
        this.$refs.tableRef.toggleRowSelection(row, flag);
    },
    resetPageNum(data) {
      if (data) {
        this.condition = data;
      }
      this.pageNum = 1;
      if (this.url) {
        this.search(this.condition);
      }
    },
  },
};
</script>

<style scoped lang="scss">
.wtable {
  width: 100%;

  .el-table {
    margin-bottom: 10px;
    width: 100%;
    :deep(.el-table__empty-block) {
      width: 100% !important;
      border-bottom: 1px solid #ebeef5;
    }
  }
  .edu-pagination {
    display: flex;
    align-items: center;
    .refresh {
      justify-content: flex-end;
      flex: 1;
      display: flex;
    }
  }
}
</style>
